package com.zixuan.sina.config.security;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zixuan.sina.utils.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 登录失败处理接口
 */
@Component
public class LoginFaireHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        ServletOutputStream outputStream = response.getOutputStream();
        String message=null;
        int code=500;
        if(exception instanceof AccountExpiredException){
            code=50008;
            message = "登录过期";
        }else if(exception instanceof LockedException){
            message = "账户被锁";
        }else if(exception instanceof BadCredentialsException){
            message = "用户名或密码错误";
        }else if(exception instanceof CredentialsExpiredException){
            message="密码过期";
        }else if(exception instanceof DisabledException){
            message="账户被禁用";
        }else if(exception instanceof InternalAuthenticationServiceException){
            message="账户不存在";
        }else {
            message="登陆失败";
        }
        String result = JSON.toJSONString(Result.error().code(code).message(message), SerializerFeature.DisableCircularReferenceDetect);
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
